package org.finalministry.gui.components;

import java.sql.SQLException;
import java.util.List;

import javax.swing.JComboBox;

import org.finalministry.database.dao.DaoFactory;
import org.finalministry.objects.address.Country;

public class CountrySelector extends JComboBox {

	private static final long serialVersionUID = 3313443888575912474L;

	public CountrySelector() {
		super(initCountries());
		this.setBackground(ColorSchema.getBackgroundColor());
	}

	private static String[] initCountries() {

		List<Country> list = null;

		try {
			list = DaoFactory.getInstance().getCountryDAO().getByAll();
		} catch (Exception e) {
			e.printStackTrace();
		}

		String[] countryArray = new String[list.size()];
		int x = 0;
		for (Country country : list) {
			countryArray[x] = country.getCountryIsoCode3() + " - " + country.getCountryEnglishName();
			x++;
		}

		return countryArray;
	}

	public Country getSelectedCountry() {
		try {
			return DaoFactory.getInstance().getCountryDAO().getByIsoCode3(this.getSelectedItem().toString().split(" ")[0]);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
